"""
网络资源获取的测试页面
"""
import typing
from elio import core

# 安卓端测试
# TEST_URL: typing.Final[str] = 'https://www.baidu.com'

# 网页端测试
TEST_URL: typing.Final[str] = 'http://localhost'

HEADERS: typing.Final[dict] = {}


class RequestsLayer(core.AutoRecycleLayer[core.Activity]):
    requests: core.Requests
    editor: core.WidgetEditor
    req_btn: core.WidgetButton

    async def on_create(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_create(*args, **kwargs)

    async def on_destroy(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_destroy(*args, **kwargs)

    async def on_show(self):
        await super().on_show()
        activity = self.parent
        self.requests = await core.Requests.create(activity)

        width, height = await activity.get_screen_size()
        self.editor = await core.WidgetEditor.create(activity, width, height - 50, 0, 0)
        self.req_btn = await core.WidgetButton.create(activity, width - 60, 50, 30, height - 50, '点击获取')
        await self.req_btn.set_on_click_listener(self.cb_btn)

    async def on_hide(self):
        await super().on_hide()
        await self.requests.destroy()
        await self.editor.destroy()
        await self.req_btn.destroy()

    async def on_pause(self):
        await super().on_pause()

    async def on_resume(self):
        await super().on_resume()

    async def cb_btn(self):
        """按钮点击事件"""
        await self.editor.set_text('正在获取， 请稍后...')

        code, headers, body = await self.requests.get(TEST_URL)
        body = body.decode('utf-8')
        print(f"{code=}\n{headers=}\n{body=}")

        data = body if code == 200 else '网页获取失败'
        await self.editor.set_text(data)
